package com.heima.schedule.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.shedule.dtos.Task;


import com.heima.model.shedule.pojos.Taskinfo;
import com.heima.model.shedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
@Transactional
@Slf4j
public class TaskServiceImpl implements TaskService {

    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;

    @Autowired
    private CacheService cacheService;

    /**
     * 添加任务
     *
     * @param task 任务对象
     * @return 任务id
     */
    @Override
    public long addTask(Task task) {

        //1.添加任务到数据库中
        boolean flag = addTaskDb(task);

        if (flag){
            //2.添加任务到redis
            addTaskCache(task);
        }
        return task.getTaskId();//都是同一个task
    }

    /**
     * 添加任务到数据库
     * @param task
     * @return
     */
    private boolean addTaskDb(Task task) {
        boolean flag = false;

        try {
            //添加到任务表
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task,taskinfo);
            //TODO long转date
            Date date = new Date(task.getExecuteTime());
            taskinfo.setExecuteTime(date);
            taskinfoMapper.insert(taskinfo);

            //TODO 设置taskID   数据库生成主键回填，taskinfo的id就是task的id
            task.setTaskId(taskinfo.getTaskId());


            //添加到任务日志表
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo,taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogsMapper.insert(taskinfoLogs);
            flag = true;
        } catch (BeansException e) {
            e.printStackTrace();
        }

        return flag;
    }

    /**
     * 添加任务到redis中
     * @param task
     * @return
     */
    private void addTaskCache(Task task) {
        boolean flag = false;
        String key = task.getTaskType()+"_"+""+task.getPriority();
        //获取5分钟之后的时间  毫秒值
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        long timeInMillis = calendar.getTimeInMillis();

        //2.1 如果任务的执行时间小于等于当前时间，存入list
        if (task.getExecuteTime()<= System.currentTimeMillis()){
            cacheService.lLeftPush(ScheduleConstants.TOPIC+key, JSON.toJSONString(task));
        }else if (task.getExecuteTime()<= timeInMillis){
            //2.2 如果任务的执行时间大于当前时间 && 小于等于预设时间（未来5分钟） 存入zset中
            cacheService.zAdd(ScheduleConstants.FUTURE+key,JSON.toJSONString(task),task.getExecuteTime());
        }
    }


    /**
     * 取消任务
     *
     * @param taskId
     * @return
     */
    @Override
    public boolean cancelTask(Long taskId) {
        boolean flag = false;

        //1.根据taskid删除任务,修改任务日志状态为 2(取消)
        //删除任务和更新日志
        Task task = updateDb(taskId,ScheduleConstants.CANCELLED);



        //2.删除redis中对应的任务数据，包括list和zset
        //根据上面的task删除redis中的任务数据

        if (task!=null){
            removeTaskFromCache(task);
            flag = true;
        }

        return flag;
    }


    /**
     * 从数据库中删除任务和更新任务日志
     * @param taskId
     * @param cancelled
     * @return
     */
    private Task updateDb(Long taskId, int cancelled) {

        Task task = null;
        try {
            //删除任务表中的任务
            taskinfoMapper.deleteById(taskId);

            //更新任务日志
            //先查任务日志表
            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(cancelled);
            taskinfoLogsMapper.updateById(taskinfoLogs);

            //构建返回值Task
            task = new Task();
            BeanUtils.copyProperties(taskinfoLogs, task);
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());

        } catch (BeansException e) {
            log.error("task cancel exception taskid={}", taskId);
        }

        return task;
    }


    /**
     * 删除redis中对应的任务数据，包括list和zset
     * @param task
     * @return
     */
    private void removeTaskFromCache(Task task) {
        String key = task.getTaskType()+"_"+""+task.getPriority();

        if (task.getExecuteTime()<System.currentTimeMillis()){
            cacheService.lRemove(ScheduleConstants.TOPIC+key,0,JSON.toJSONString(task));
        }else {
            cacheService.zRemove(ScheduleConstants.FUTURE+key,JSON.toJSONString(task));
        }

    }

    /**
     * 消费任务
     * @param type
     * @param priority
     * @return
     */
    @Override
    public Task poll(int type, int priority) {
        Task task = null;
        try {
            String key = type+"_"+priority;
            //从redis的list中pop数据
            String s = cacheService.lRightPop(ScheduleConstants.TOPIC + key);

            //删除任务&修改日志状态
            if (StringUtils.isNotBlank(s)){
                task = JSON.parseObject(s,Task.class);
                updateDb(task.getTaskId(), ScheduleConstants.EXECUTED);//已执行
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("poll task exception");
        }

        return task;
    }

    @Scheduled(cron = "0 */1 * * * ?")//表示每分钟执行一次
    public void refresh() {

        String token = cacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);//过期时间
        //如果token有值，说明未加锁，可执行下面的代码
        if (StringUtils.isNotBlank(token)){

            System.out.println(System.currentTimeMillis() / 1000 + "执行了定时任务");

            // 获取所有未来数据集合的key值
            Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");// future_*
            for (String futureKey : futureKeys) { // future_250_250

                String topicKey = ScheduleConstants.TOPIC + futureKey.split(ScheduleConstants.FUTURE)[1];
                //获取该组key下当前需要消费的任务数据
                Set<String> tasks = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());
                if (!tasks.isEmpty()) {
                    //将这些任务数据添加到消费者队列中
                    cacheService.refreshWithPipeline(futureKey, topicKey, tasks);
                    System.out.println("成功的将" + futureKey + "下的当前需要执行的任务数据刷新到" + topicKey + "下");
                }
            }
        }
    }

    /**
     * 数据库任务定时同步到redis
     */

    @Scheduled(cron = "0 */5 * * * ?")//每5分钟执行一次
    @PostConstruct//启动微服务时直接执行该方法，即初始化的方法
    public void reloadData(){
        //第一步：清理缓存中的数据
        clearCache();

        //第二步：查询小于未来5分钟的所有任务
        LambdaQueryWrapper<Taskinfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        //获取5分钟之后的时间  毫秒值
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);

        lambdaQueryWrapper.lt(Taskinfo::getExecuteTime,calendar.getTime());
        List<Taskinfo> taskinfoList = taskinfoMapper.selectList(lambdaQueryWrapper);

        //第三步：新增任务到redis
        for (Taskinfo taskinfo : taskinfoList) {
            Task task = new Task();
            BeanUtils.copyProperties(taskinfo,task);
            task.setExecuteTime(taskinfo.getExecuteTime().getTime());
            addTaskCache(task);
        }
        
    }


    public void clearCache(){
        // 删除缓存中未来数据集合和当前消费者队列的所有key
        Set<String> topicKeys = cacheService.scan(ScheduleConstants.TOPIC + "*");
        Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        cacheService.delete(topicKeys);
        cacheService.delete(futureKeys);

    }
}
